//
//  CFUtility.m
//  CFFinanceProject
//
//  Created by chunfeng on 2018/4/9.
//  Copyright © 2018年 xiaowen. All rights reserved.
//

#import "CFUtility.h"
//#import "NSString+ToDate.h" checkoutTwoTimeStringVaryMoreThenTenMin方法需要倒入



/**
 获取IP地址需要导入
 */
#import <ifaddrs.h>
#import <arpa/inet.h>

#import <CommonCrypto/CommonDigest.h> //md5需导入文件

@implementation CFUtility


/**
 *提示框,Tim添加
 */
+ (void)showTips:(NSString *)tips
{
    if (!tips)return;
    MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    hud.mode=MBProgressHUDModeText;
    hud.detailsLabel.text=tips;
    hud.detailsLabel.font = [UIFont systemFontOfSize:15];
    hud.removeFromSuperViewOnHide=YES;
    hud.minSize=CGSizeMake(140, 25);
    [hud showAnimated:YES];
    [hud hideAnimated:YES afterDelay:1.2];
}


+ (void)setExtraCellLineHidde:(UITableView *)tableView tabHeader:(BOOL) header tabFooter:(BOOL) footer
{
    UIView *view =[ [UIView alloc]init];
    view.backgroundColor = [UIColor clearColor];
    if (!header) {
        [tableView setTableHeaderView:view];
    }
    if (!footer) {
        [tableView setTableFooterView:view];
    }
}

//MD5加密
+(NSString *) md5: (NSString *) inPutText
{
    if (!inPutText) {
        return inPutText;
    }
    const char *cStr = [inPutText UTF8String];
    unsigned char result[16];
    CC_MD5( cStr, (int)strlen(cStr), result );
    NSString *md5Result = [NSString stringWithFormat:
                           @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                           result[0], result[1], result[2], result[3],
                           result[4], result[5], result[6], result[7],
                           result[8], result[9], result[10], result[11],
                           result[12], result[13], result[14], result[15]
                           ];
    return md5Result;
}
//判断非空
+(NSString *)NSNULLString:(NSString *)string{
    if( [string isEqualToString:@""]||[string length]==0||[[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0){
        return string;
    }
    return nil;
}

//限制特殊字符不能输入@
+(int) XZInputText:(NSString *) stringText{
    NSCharacterSet *nameCharacters = [NSCharacterSet
                                      characterSetWithCharactersInString:@"`~!@#$%^&*()+=|{}':;',\\[\\].<>?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？"];
    NSRange userNameRange = [stringText rangeOfCharacterFromSet:nameCharacters];
    
    if (userNameRange.location != NSNotFound) {
        return 0;//包含特殊字符
    }else{
        return 1;
    }
    return 1;
    
    //用法
    
    /**
     if ([self XZInputText:_userAddress.text]==0) {
     MessageSHAREShow(@"不能输入特殊字符");
     return false;
     }
     */
}
//判断密码
+(BOOL)CheckInput:(NSString *)_text{
    NSString *Regex = @"\\w{6,16}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", Regex];
    return [emailTest evaluateWithObject:_text];
}

//检测手机号
+ (BOOL)validateMobile:(NSString *)mobileNum
{
    if(mobileNum.length == 0 || mobileNum == nil || mobileNum.length < 11) return NO;
    
    NSString *Regex = @"^(13[0-9]|15[0-9]|18[0-9]|17[0-9]|147)\\d{8}$";//以前用的
    NSPredicate *phone = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",Regex];
    return [phone evaluateWithObject:mobileNum];
}
//获取IP地址
+ (NSString *)getIPAddress {
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while(temp_addr != NULL) {
            if(temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    // Free memory
    freeifaddrs(interfaces);
    return address;
}


//!!!!: 风火轮加载信息
/**
 *  风火轮加载信息
 *
 *  @param _targetView 对象
 *  @param _msg        提示信息
 */
+ (void)showMBProgress:(UIView *)_targetView message:(NSString *)_msg {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        MBProgressHUD *progressHUD = [[MBProgressHUD alloc] initWithView:_targetView];
        progressHUD.mode = MBProgressHUDModeIndeterminate;
        [progressHUD showAnimated:YES];
        progressHUD.label.text = _msg;
        [_targetView addSubview:progressHUD];
    });
    
}

+ (void)hideMBProgress:(UIView*)_targetView{
    
    [MBProgressHUD hideHUDForView:_targetView animated:YES];
}

/**
 *  将时间戳转换为指定格式时时间
 *
 *  @param strTimestamp  传入的时间戳
 *  @param strDateFormat 时间的格式
 *
 *  @return 返回的时间
 */
+ (NSString *)getTimeWithTimestamp:(NSString *)strTimestamp WithDateFormat:(NSString *)strDateFormat
{
    
    /**
     
     时间戳转换
     
     */
    if ([strTimestamp isEqualToString:@"0"]||[strTimestamp length]==0)
    {
        return @"";
    }
    
    long long time;
    if (strTimestamp.length == 10) {
        time = [strTimestamp longLongValue];
    }
    if (strTimestamp.length == 13){
        time = [strTimestamp longLongValue]/1000;
    }
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:time];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:strDateFormat];
    NSString *strTime = [formatter stringFromDate:date];
    return strTime;
    
    
    
    /**
     
     - returns:  时间转换yyyy-MM-dd
     
     重点 服务器返回的是一个yyyy-MM-dd HH:mm:ss格式  需要先获取一个格式一样的本地时间,才可以进行正常转换
     
     */
    
    //
    //    NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];
    //
    //    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    //
    //    NSString *dateString=[NSString stringWithFormat:@"%@", strTimestamp];
    //
    //    NSDate *date =[dateFormat dateFromString:dateString];
    //
    //    NSDateFormatter* dateFormat2 = [[NSDateFormatter alloc] init];
    //
    //    [dateFormat2 setDateFormat:strDateFormat];
    //
    //    NSString *publishtimeStr = [dateFormat2 stringFromDate:date ];
    //
    //    return  publishtimeStr;
}


/**
 *  根据目标字符判断该字符是否存在值
 *
 *  @param string 目标字符
 *
 *  @return yes->存在
 */
+ (BOOL)checkoutStringIsExistWithTargetString:(NSString *)string {
    if (string == nil) {
        return NO;
    }
    
    if ([string isEqual:[NSNull null]]) {
        return NO;
    }
    
    if ([string isEqualToString:@""]) {
        return NO;
    }
    
    if ([string isEqualToString:@"nil"]) {
        return NO;
    }
    
    if ([string isEqualToString:@"null"]) {
        return NO;
    }
    
    if ([string isEqualToString:@"Nil"]) {
        return NO;
    }
    
    if ([string isEqualToString:@"NULL"]) {
        return NO;
    }
    
    if ([string isEqualToString:@"(nil)"]) {
        return NO;
    }
    
    if ([string isEqualToString:@"(null)"]) {
        return NO;
    }
    
    if ([string isEqualToString:@"(Nil)"]) {
        return NO;
    }
    
    if ([string isEqualToString:@"(NULL)"]) {
        return NO;
    }
    
    return YES;
}



//+ (BOOL)checkoutTwoTimeStringVaryMoreThenTenMin:(NSString *)firstTime secondTime:(NSString *)secondTime {
//    NSTimeInterval back = 10*60;
//    NSDate *secondDate = [secondTime toAllInfoDate];
//    NSDate *resultData = [NSDate dateWithTimeInterval:back sinceDate:secondDate];
//    NSTimeInterval firstTimeInterval = [firstTime toTimeInterval1970];
//    NSTimeInterval secondTimeInterval = [resultData timeIntervalSince1970];
//    if (firstTimeInterval >= secondTimeInterval) {
//        return YES;
//    } else {
//        return NO;
//    }
//
//}


+ (BOOL)stringContainsEmoji:(NSString *)string
{
    __block BOOL returnValue = NO;
    
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length])
                               options:NSStringEnumerationByComposedCharacterSequences
                            usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                                const unichar high = [substring characterAtIndex: 0];
                                
                                // Surrogate pair (U+1D000-1F9FF)
                                if (0xD800 <= high && high <= 0xDBFF) {
                                    const unichar low = [substring characterAtIndex: 1];
                                    const int codepoint = ((high - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000;
                                    
                                    if (0x1D000 <= codepoint && codepoint <= 0x1F9FF){
                                        returnValue = YES;
                                    }
                                    
                                    // Not surrogate pair (U+2100-27BF)
                                } else {
                                    if (0x2100 <= high && high <= 0x27BF){
                                        returnValue = YES;
                                    }
                                }
                            }];
    
    return returnValue;
}

+ (NSDate *)getInternetDate{
    NSString *urlString = @"http://m.baidu.com";
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString: urlString]];
    [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
    [request setTimeoutInterval: 2];
    [request setHTTPShouldHandleCookies:FALSE];
    [request setHTTPMethod:@"GET"];
    NSHTTPURLResponse *response;
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
    
    NSString *date = [[response allHeaderFields] objectForKey:@"Date"];
    date = [date substringFromIndex:5];
    date = [date substringToIndex:[date length]-4];
    NSDateFormatter *dMatter = [[NSDateFormatter alloc] init];
    dMatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    [dMatter setDateFormat:@"dd MMM yyyy HH:mm:ss"];
    NSDate *netDate = [[dMatter dateFromString:date] dateByAddingTimeInterval:60*60*8];
    
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: netDate];
    NSDate *localeDate = [netDate  dateByAddingTimeInterval: interval];
    return localeDate;
}

+ (NSString *)dencode:(NSString *)base64String
{
    //NSData *base64data = [string dataUsingEncoding:NSUTF8StringEncoding];
    
    NSData *data = [[NSData alloc]initWithBase64EncodedString:base64String options:NSDataBase64DecodingIgnoreUnknownCharacters];
    
    NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    
    return string;
}

+ (NSString *)encode:(NSString *)string
{
    //先将string转换成data
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    
    NSData *base64Data = [data base64EncodedDataWithOptions:0];
    
    NSString *baseString = [[NSString alloc]initWithData:base64Data encoding:NSUTF8StringEncoding];
    
    return baseString;
}

+ (NSString *)replaceUnicode:(NSString *)unicodeStr {
    if (![CFUtility checkoutStringIsExistWithTargetString:unicodeStr]) {
        return @"";
    }
    
    NSString *tempStr1 = [unicodeStr stringByReplacingOccurrencesOfString:@"\\u"withString:@"\\U"];
    NSString *tempStr2 = [tempStr1 stringByReplacingOccurrencesOfString:@"\""withString:@"\\\""];
    NSString *tempStr3 = [[@"\""stringByAppendingString:tempStr2]stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString* returnStr = [NSPropertyListSerialization propertyListFromData:tempData
                                                           mutabilityOption:NSPropertyListImmutable
                                                                     format:NULL
                                                           errorDescription:NULL];
    if ([returnStr isNullOrEmpty]) {
        return unicodeStr;
    }else{
        return [returnStr stringByReplacingOccurrencesOfString:@"\\r\\n"withString:@"\n"];
    }
}

+(NSString *)encodeToUnicode:(NSString *)string{
    NSUInteger length = [string length];
    NSMutableString *s = [NSMutableString stringWithCapacity:0];
    for (int i = 0;i < length; i++)
    {
        unichar _char = [string characterAtIndex:i];
        //判断是否为英文和数字
        //        if (_char <= '9' && _char >= '0')
        //        {
        //            [s appendFormat:@"%@",[string substringWithRange:NSMakeRange(i, 1)]];
        //        }
        //        else if(_char >= 'a' && _char <= 'z')
        //        {
        //            [s appendFormat:@"%@",[string substringWithRange:NSMakeRange(i, 1)]];
        //        }
        //        else if(_char >= 'A' && _char <= 'Z')
        //        {
        //            [s appendFormat:@"%@",[string substringWithRange:NSMakeRange(i, 1)]];
        //        }
        //        else
        //        {
        [s appendFormat:@"\\u%x",[string characterAtIndex:i]];
        //       }
    }
    return s;
}

+ (UIViewController *) getVC:(NSString *)vcId Storyboard:(NSString *)Storyboard {
    return [[UIStoryboard storyboardWithName:Storyboard bundle:nil] instantiateViewControllerWithIdentifier:vcId];
}

@end
